define(['jquery',"bootstrap","bbcare",'scprit/patientsQuestionnaire/vm/common.js',
    "scprit/patientsQuestionnaire/vm/womenHealthQuestionnaire.ui.js",
    "scprit/patientsQuestionnaire/vm/womenHealthQuestionnaire.servers.js"
    ],function($,bootstrap,$bb,$common,$ui,$servers){
    var event = {};
    /*
    * 提交：
     */
    var scoreObjDeal_osi = function(scoreObj,infoParams){
        var positionsId = {};
        for(var item in scoreObj["ques"]){
            var items = item;
            if(infoParams.evaType == "GLE"){
                items = item.split("-").join('.');
            }
            positionsId[items] = scoreObj["ques"][item].join(";")
        }
        return positionsId;
    }
    /*
    *  长期事件 -- 获取N值：
     */
    var getN = function(obj){
        var n = "";
        var startTime = obj.startTime;
        var endTime = obj.endTime == "至今" ? $common.getNowFormatDate():obj.endTime;
        var diff = $common.dateDiff(startTime,endTime);
        if(diff*1 > 182.5){//大于半年：
            n = 2;
        }else{ //小于半年
            n = 1;
        }
        return n ;
    }
    
   //分数格式处理：
    var scoreObjDeal = function(scoreObj){
        var positionsId = {};
        var ques = scoreObj.ques;
        var manyTimes = scoreObj.manyTimes;
        for(var item in ques) {
            //获取大题号：
            var fuId = item.substring(0, item.indexOf("."));
            if (!positionsId[fuId]) {
                positionsId[fuId] = {};
            }
            var childId = item.substring(item.indexOf(".") + 1);
            if(ques[fuId + ".1"] != "A"){
                if (childId != "5") {
                    positionsId[fuId][childId] = ques[item];
                } else {
                    if (ques[item].indexOf("{") >= 0 && ques[item].indexOf("}") >= 0) {//时间段类型：
                        var value = JSON.parse(ques[item]);
                        positionsId[fuId][childId] = getN(value);
                    } else {//一过性事件：时间点：
                        var n = 0, lens = 0;
                        if (manyTimes[item]) {
                            var many = manyTimes[item];
                            for (var its in many) {
                                if (many[its].value) {
                                    lens++;
                                }
                            }
                        }
                        if (ques[item]) {
                            n = 1;
                        }
                        positionsId[fuId][childId] = lens + n;
                    }
                }
            }else if(ques[fuId + ".1"] == "A" && childId == "1"){
                positionsId[fuId][childId] = ques[item];
            }
        }
        return positionsId;
    }
     /*
    *  去提交：
     */
    var toSubmitFn = function(){
        //提交前的数据处理：
        var params = $(this).data("params");
        var scoreObj = params.scoreObj ;
        var infoParams = params.infoParams;
        var positionsId;
        if(infoParams.evaType == "LES"){
            positionsId = scoreObjDeal(scoreObj)
        }else{
            positionsId = scoreObjDeal_osi(scoreObj,infoParams)
        }
        var inParams = {
            "userId":infoParams.userId,
            "postionScores":scoreObj,
            "postionIds":positionsId,
            "examinationPaperName": infoParams.evaType,
            "deptId":infoParams.deptId,
            "queueId":infoParams.queueId
        };
        var submitCallback = function(data){
            if(!data.success){
                data.data={};
            }
            data.data.userId = infoParams.userId;
            data.data.queueId = infoParams.queueId;
            data.data.deptId = infoParams.deptId;
            data.data.evaType = infoParams.evaType;
            data.data.deptId = infoParams.deptId;
            localStorage.setItem("submitStatus",JSON.stringify(data));
            $common.getHtml({"url":"page/patientsQuestionnaire/html/success.html"});
        };
        $servers.saveQuestion(inParams,submitCallback);
    };
    /*
    * 提交：
     */
    var submitFn = function(infoParams,scoreObj){
        var className = "toSubmitModal";
        $ui.toSubmitInit({"id":"#myModalbox","data":{"className":className}});
        $("#myModalbox").find("."+className).modal({"backdrop":'static',"show":true});
        $ui.lesSubmitInit({
            "dom":$("."+className).find(".modal-body"),
            "evaType":infoParams.evaType
        });
        //返回修改：
        $("#backModify").click(function(){
            $("#myModalbox").find("."+className).modal("hide");
        });
        //去提交：
        $("#toSubmit").data("params",{"scoreObj":scoreObj,"infoParams":infoParams});
        $("#toSubmit").click(toSubmitFn);
    }
    //上一题、下一题；
    var topicSwitching = function(questions,scoreObj,dom,quesLens,infoParams){
        var group = $(dom).attr("group");
        var item = $(dom).attr("item");
        var nowQuesId = $("#questionnaire").find("div[quesType='les']").attr("id");
        var fuId = nowQuesId.substring(0,nowQuesId.indexOf("."));
        var ques = nowQuesId;
        //获取下一个加载的题目：
        if(group == "prev"){//上：

            if(item == "group"){//上一组
                if(fuId*1 > 1){
                    ques = (fuId*1 - 1)+".1"; 
                }else{
                    $common.toastShow("目前已经是第一组",2000);
                }
            }else if(item == "question"){//上一题
                if(nowQuesId*1 > 1.1){
                    if((nowQuesId*1 == fuId + ".1") && (!scoreObj["ques"][fuId-1+".1"] || scoreObj["ques"][fuId-1+".1"] == "A")){
                        ques = fuId-1+".1";
                    }else{
                        if(nowQuesId.substring(nowQuesId.indexOf(".")+1) == 1){
                            if(scoreObj["ques"][fuId-1+".1"] != "A" && scoreObj["ques"][fuId-1+".3"] == "A"){
                                ques = (nowQuesId*1 - 0.8).toFixed(1);
                            }else{
                                ques = (nowQuesId*1 - 0.6).toFixed(1);
                            }
                        }else{
                           ques = (nowQuesId*1 - 0.1).toFixed(1); 
                        }
                    }
                }else{
                    $common.toastShow("目前已经是第一题",2000);
                }
            }
        }else if(group == "next"){//下：
            var type = $("#questionnaire").find("div[quesType='les']").attr("type");
            var flag = false;
            //如果当前事件未发生，则后面几题可以不做；如果发生了，必须做：
            if(scoreObj["ques"][fuId+".1"] == "A"){
                flag = true;
            }else{
                if(type == "timeQuantum"){
                    if(scoreObj["ques"][nowQuesId]){
                    var res = JSON.parse(scoreObj["ques"][nowQuesId]);
                        if(res.endTime && res.startTime){flag = true;}
                    }
                }else{
                    if(scoreObj["ques"][nowQuesId]){flag = true;}
                }
            }
            if(flag){
                if(item == "group"){//下一组：
                    //如果当前组选A，可以进行下一组，反之，不可以进行下一组
                    if(scoreObj["ques"][fuId+".1"] == "A"){
                        if(nowQuesId == quesLens+".1"){
                            submitFn(infoParams,scoreObj);
                        }else{
                            ques = (fuId*1 + 1)+".1"; 
                        }
                    }else{
                        if(scoreObj["ques"][fuId+".2"] && scoreObj["ques"][fuId+".3"] && scoreObj["ques"][fuId+".4"] && scoreObj["ques"][fuId+".5"]){
                            if(nowQuesId == quesLens+".5"){
                                submitFn(infoParams,scoreObj);
                            }else{
                               ques = (fuId*1 + 1)+".1";  
                            }
                        }else{
                            $common.toastShow("当前组的题目还未做完，不可以进行下一组",2000);
                        }
                    }
                }else if(item == "question"){//下一题：

                    //如果当前组的第一题选A，可直接进入下一组，反之，进入当前组的下一题：
                    if(scoreObj["ques"][fuId+".1"] == "A" || (scoreObj["ques"][fuId+".1"] != "A" && scoreObj["ques"][fuId+".3"] && scoreObj["ques"][fuId+".3"] == "A" )){//如果未发生：
                        if(nowQuesId == quesLens+".1" || nowQuesId == quesLens+".3"){
                            submitFn(infoParams,scoreObj);
                        }else{
                            ques = fuId*1 + 1 + ".1";
                        }
                    }else{
                        //如果最后一题，提交：
                        if(nowQuesId == quesLens+".5"){
                            submitFn(infoParams,scoreObj);
                        }else{
                            if(nowQuesId.substring(nowQuesId.indexOf(".")+1) == 5){
                                ques = (nowQuesId*1 + 0.6).toFixed(1);
                            }else{
                                ques = (nowQuesId*1 + 0.1).toFixed(1);
                            }
                        }
                    }
                }
            }else{
                $common.toastShow("当前题目未做完，不可以进行下一题",2000);
                return 
            }
        }
        //渲染答案：
        if(scoreObj['ques'][ques]){
            if(scoreObj['ques'][ques].indexOf("{") >=0 && scoreObj['ques'][ques].indexOf("}") >= 0){
                var res = JSON.parse(scoreObj["ques"][ques]);
                questions[ques].value = res.startTime;
                questions[ques].endTime = res.endTime;
            }else{
                questions[ques].value = scoreObj['ques'][ques];
            }
        }
        if(scoreObj['manyTimes'][ques]){
            var manyTimes = [];
            for(var item in scoreObj['manyTimes'][ques]){
                manyTimes.push(scoreObj['manyTimes'][ques][item]);
            }
            questions[ques].manyTimes = manyTimes;
            questions[ques].manyLens = manyTimes.length;
        }
        //判断右侧答题进度栏的状态：LES
        var fuId = ques.substring(0,ques.indexOf("."));
        var index = getIndex(fuId*1);
        //做完的样式：
        if(index > 0){
            $(".project_schedule li").eq(index-1).addClass("done").find(".schedule-title").html('<i class="fa fa-check-circle" aria-hidden="true"></i>');
        }
        $(".project_schedule li").eq(index).addClass("doing").siblings().removeClass('doing');
        $(".project_schedule li").eq(index).find(".schedule-title").html('<i class="fa fa-crosshairs" aria-hidden="true"></i>');
        $(".project_schedule li").eq(index).find(".doneNo").html(questions[ques].indexNo);
        
        $ui.questionTypeInit({"id":"#questionnaire","data":questions[ques]});
        $("#groupNo").html(questions[ques].lens);
    };
    var getIndex = function(id){
        //1-28:与家庭相关的题目；29-41：工作学习中的问题；42-48：社会其他问题；49-50：其他问题：
        var index = 0;
        if(id <= 28 && id >= 1){
            index = 0;
        }else if(id <= 41 && id >= 29){
            index = 1;
        }else if(id <= 48 && id >= 42){
            index = 2;
        }else{
            index = 3;
        }
        return index;
    }

    //LES单选：时间，性质，影响程度；
    var quesSingleTabFn = function(scoreObj,dom){
        $(dom).addClass("link_checked").siblings().removeClass("link_checked");
        var nowId = $(dom).parents('div[type="singleElection"]').attr("id");
        scoreObj["ques"][nowId] = $(dom).attr("name");
        setTimeout(function(){
            $("#box").find('.ques-click-group-les button[group="next"][item="question"]').click();
        },100);
    };

    //发生多次：
    var manyTimesFn = function(scoreObj,dom){
        if(!$(dom).parent().siblings().find('input').val()){
            $common.toastShow("该事件发生年月还未填写",2000);
            return;
        }
        var lens = $(dom).parents("div[type='timePoint']").find(".ques_names").find('div.ques_date').length;
        var num = lens+1;
        var maxTime = $common.getNowFormatDate();
        var h = '<div class="cleatfix ques_date" number = "'+num+'">'+
                    '<div>'+
                        '<input type="date" name="manyTimes" max="'+maxTime+'" class="form-control" />'+
                    '</div>'+
                    '<div>'+
                        '<button class="btn btn-pri manyTimes" id="manyTimes">发生多次</button>'+
                    '<button class="btn btn-pri none-btn" id="noneDate">没有了</button>'+
                    '</div>'+
                '</div>';
        $(dom).parents("div[type='timePoint']").find(".ques_names").append(h);
        $(dom).siblings(".none-btn").remove();
        $(dom).remove();
    };
    var manyTimesChangeFn = function(scoreObj,dom){
        var nowId = $(dom).parents('div[type="timePoint"]').attr("id");
        var arr = [];//获取已经填写过的日期：
        $("input[name='manyTimes']").each(function(){
            if($(this).val()){
                arr.push($(this).val());
            }
        });
        var val = $(dom).val();
        //判断出现了几次：
        var no = 0;
        for(var i = 0;i<arr.length;i++){
            if(arr[i] == val){++no;}
            if(no > 1){
                $(dom).val('');
                $common.toastShow("已经输入过该日期",2000);
                break;
            }
        }
        if($(dom).parents(".ques_date").siblings(".ques_name").html()){
            scoreObj['ques'][nowId] = val;
        }else{
            var num = $(dom).parents('div.ques_date').attr("number");
            if(!scoreObj['manyTimes'][nowId]){
                scoreObj['manyTimes'][nowId] = {};
            }
            scoreObj['manyTimes'][nowId][num] = {"value":val,"number":num};
        }
    };

    //持续时间：时间段：
    var timeQuantumFn = function(scoreObj,dom){
        var startTime = $(dom).parents('div[type="timeQuantum"]').find("input[name='startTime']").val();
        if(!startTime){
            $common.toastShow("请先选择开始时间",2000);
            return
        }
        var nowId = $(dom).parents('div[type="timeQuantum"]').attr("id");
        var val;
        var name = $(dom).attr("name");
        if(!scoreObj["ques"][nowId]){
            val = {};
        }else{
            val = JSON.parse(scoreObj["ques"][nowId])
        }
        var value;
        $(dom).addClass("link_checked").siblings().removeClass("link_checked");
        if($(dom).html() == "至今"){
            $(dom).siblings("input").val("").css("display","none");
            value = $(dom).html();
        }else{
            $(dom).siblings("input").css("display","block");
            value = $(dom).siblings("input[name='endTime']").val();
        }
        val[name] = value;
        scoreObj["ques"][nowId] = JSON.stringify(val);
    };
    var timeQuantumChangeFn = function(scoreObj,dom){
        var nowId = $(dom).parents('div[type="timeQuantum"]').attr("id");
        var name = $(dom).attr("name");//[name='startTimes']
        if(name == "startTime"){//控制结束时间不能输入开始时间以前的数值：
            $('input[name="endTime"]').attr("min",$(dom).val()).val('');
        }
        var val;
        if(!scoreObj["ques"][nowId]){
            val = {};
        }else{
            val = JSON.parse(scoreObj["ques"][nowId])
        }
        val[name] = $(dom).val();
        scoreObj["ques"][nowId] = JSON.stringify(val);
    };
    //生活事件量表：
    event.init = function(questions,scoreObj,quesLens,infoParams){
        //上下题切换：
        $("#box").on("click",".ques-click-group-les button",function(){
            var _this = this;
            topicSwitching(questions,scoreObj,_this,quesLens,infoParams);
        });
        /*
        * LES单选：时间，性质，影响程度
        * */
        $("#box").on("click","div[type='singleElection'][quesType='les'] .linkage_tab",function(){
            var _this = this;
            quesSingleTabFn(scoreObj,_this);
        });
        /*
        * LES发生多次：时间点
        * */
        $("#box").on("click","div[type='timePoint'][quesType='les'] #manyTimes",function(){
            var _this = this;
            manyTimesFn(scoreObj,_this);
        });

        /*
        * 发生多次时间点： input监听事件：manyTimes
         */
        $("#box").on("change","div[type='timePoint'][quesType='les'] input[name='manyTimes']",function(){
            var _this = this;
            manyTimesChangeFn(scoreObj,_this);
        });

        /*
        * 持续时间：时间段：
        * */
        $("#box").on("click","div[type='timeQuantum'][quesType='les'] .linkage_tab",function(){
            var _this = this;
            timeQuantumFn(scoreObj,_this);
        });

        /*
         * 时间段监听： input监听事件：
         */
        $("#box").on("change","div[type='timeQuantum'][quesType='les'] input",function(){
            var _this = this;
            timeQuantumChangeFn(scoreObj,_this);
        });

        /*
        * 自动跳入下一题：
         */
        $("#box").off("click","#noneDate");
        $("#box").on("click","#noneDate",function(){
            $("#box").find(".ques-click-group-les button[group='next'][item='question']").click();
        }); 
    };
    /*
    * 妇女健康调查问卷：
    *
     */
    /*
    * 上下题目跳转：
     */
    var topicSwitchingOSI = function(questions,scoreObj,dom,infoParams,length){
        var nextList;
        var group = $(dom).attr("group");
        var nowQuesId = $("#questionnaire").find("div[quesType='osi']").attr("id");
        var questionsnaire = $(dom).parents('.questionnaire_operate').siblings(".questionnaire");
        var type = questionsnaire.find('div[quesType="osi"]').attr("type");

        var flag = true;//是否完成；
        if(type == "blank" || type == "blankList"){
            flag = quesBlankFn_osi(scoreObj,dom);
        }else if (type == "single"){
            flag = quesSingleSave_osi(scoreObj,dom);
        }else if (type == "checkbox"){
            flag = quesCheckboxSave_osi(scoreObj,dom);
        }else if(type == "linkage"){
            flag = quesLinkageSaveFn_osi(scoreObj,dom);
        }else{
            if(!scoreObj["ques"][nowQuesId]){
                flag = false;
            }
        }
        var nowList = $("#questionnaire").find("div[quesType='osi']").attr("number");
        nextList = nowList;
        if(group=="prev"){
            if(nowList == "1"){
                $common.toastShow("目前已经是第一题",1500);
                return;
            }else{
                nextList = nowList*1 - 1;
                flag = true;
            }
        }else if(group=="next"){
            if(flag && flag!="emo" && flag!="num"){
                if(nowList == length){
                    submitFn(infoParams,scoreObj)
                }else{
                    nextList = nowList*1 + 1
                }
            }else{
                if(flag == "emo"){
                    $common.toastShow("不能输入表情符号",1500);
                    return;
                }else if(flag == "num"){
                    $common.toastShow("请输入数字",1500);
                    return;
                }else{
                    $common.toastShow("当前题目还未做完，不可以进入下一题",2000);
                }
            }
        }else{
            if(flag && flag != 'num' && flag != "emo"){
                nextList = $(dom).attr("item")*1;
                if(scoreObj["ques"][questions[nextList].id]){
                    flag = true;
                }
            }else if(!flag ||  flag == 'num' || flag == "emo"){
                var dd = questions[$(dom).attr("item")*1].id;
                if(scoreObj["ques"][dd]){
                    nextList = $(dom).attr("item")*1;
                    flag = true;
                }else{
                    $common.toastShow("当前题目还未做完，不可以进入下一题",2000);
                }
            }
        }
        //渲染记录：
        var nextId = questions[nextList].id;
        var nextType = questions[nextList].type;
        if(nextId){
            var prefix = nextId.substring(0,1);//获取阶段
            var preNo;//获取当前阶段的当前题号
            if(infoParams.evaType =="GLE"){
                prefix = questions[nextList].itemTitle;
                preNo = nextId.split("-")[1];
            }else{
                preNo = nextId.substring(1)
            }
        }
        historyData(scoreObj,questions,nextList,nextId,nextType);
        if(flag && flag!="emo" && flag!="num"){
            $("#groupNo").html(questions[nextList].length);
            event.btnGroupCss(nextList,length);
            $("#ques-click-group-osi").find('button[type][item="'+nextList+'"]').addClass("btn-checked").siblings().removeClass("btn-checked");
            $ui.questionTypeInit2({"id":"#questionnaire","data":questions[nextList]});
            $(".project_schedule").find('li[group="'+prefix+'"]').prev().addClass("done").find(".schedule-title").html('<i class="fa fa-check-circle" aria-hidden="true"></i>');
            $(".project_schedule").find('li[group="'+prefix+'"]').addClass("doing").siblings().removeClass('doing');
            $(".project_schedule").find('li.doing').find(".schedule-title").html('<i class="fa fa-crosshairs" aria-hidden="true"></i>');
            $(".project_schedule").find('li.doing').find(".doneNo").html(preNo);
            if(nextType == "linkage" || nextType == "blank"){
                historyData2(scoreObj,questions,nextList,nextType);
            }
        }
    }
    var historyData2 = function(scoreObj,questions,nextList,nextType){
        var questionsnaire = $(".questionnaire");
        if(questions[nextList].list){
            questionsnaire.find('.panel-body>div[type]').each(function(){
                var id=$(this).attr("id");
                var type=$(this).attr("type");
                if(type == "blank"){
                    if(scoreObj["ques"][id]){
                        $(this).find("input").each(function(index){
                            $(this).val(scoreObj["ques"][id][index]);
                        });
                    }
                }
            })
        }else if(nextType == "blank"){
            questionsnaire.find('div[type="blank"]').each(function(){
                var id=$(this).attr("id");
                if(scoreObj["ques"][id]){
                    $(this).find("input").each(function(index){
                        $(this).val(scoreObj["ques"][id][index]);
                    });
                }
            });
        }
    }
    var historyData = function(scoreObj,questions,nextList,nextId,nextType){
        delete questions[nextList].value;
        delete questions[nextList].extralSingle;
        delete questions[nextList].valueLens;
        if(scoreObj["ques"][nextId] && scoreObj["ques"][nextId].length > 0){
            if(nextType == "blank"){
                questions[nextList].value = scoreObj["ques"][nextId][0];
            }else if(nextType == "single" || nextType == "checkbox"){
                optionsStatus(questions[nextList],questions[nextList].option,scoreObj["ques"][nextId],nextType)
            }else if(nextType == "blankList"){
                var scoreArr = [];
                var score = scoreObj["ques"][nextId];
                for(var i = 0;i<score.length;i++){
                    scoreArr.push({"no":i+1,"val":score[i]});
                }
                questions[nextList].value = scoreArr;
                questions[nextList].valueLens = scoreArr.length;
            }else if(nextType == "linkage"){
                dealLinkage(scoreObj,questions,nextList,nextId,nextType);
            }
        }else{
            if(nextType == "linkage"){
                dealLinkage(scoreObj,questions,nextList,nextId,nextType);
            }
        }
    }
    var dealLinkage = function(scoreObj,questions,nextList,nextId,nextType){
        for(var i = 0 ;i< questions[nextList].list.length;i++){
            var id = questions[nextList].list[i].id;
            delete questions[nextList].list[i].value;
            delete questions[nextList].list[i].extralSingle;
            delete questions[nextList].list[i].value;
            delete questions[nextList].list[i].valueLens;
            if(scoreObj["ques"][id] && scoreObj["ques"][id].length > 0){
                var type = questions[nextList].list[i].type;
                if(type == "blank"){
                    questions[nextList].list[i].value = scoreObj["ques"][id][0];
                }else if(type == "single" || type == "checkbox"){
                    optionsStatus(questions[nextList].list[i],questions[nextList].list[i].option,scoreObj["ques"][id],type)
                }else if(type == "blankList"){
                    var scoreArr = [];
                    var score = scoreObj["ques"][id];
                    if(scoreObj["ques"][id].length > 0){
                        for(var k = 0;k<score.length;k++){
                            scoreArr.push({"no":k+1,"val":score[k]});
                        }
                        questions[nextList].list[i].value = scoreArr;
                        questions[nextList].list[i].valueLens = scoreArr.length;
                    }
                }else if(type == "blankSingle"){
                    var scoreArr = [];
                    var score = scoreObj["ques"][id];
                    var lens = scoreObj["ques"][id].length;
                    if(lens > 0){
                        if(lens > 1){
                            for(var k = 0;k<score.length;k++){
                                if(k!= 0 && k!= (lens-1)){
                                    scoreArr.push({"no":k+1,"val":score[k],"maxDate":$common.getNowFormatDate()});
                                }
                            }
                            for(var m = 0 ; m<questions[nextList].list[i].option.length;m++){
                                if(questions[nextList].list[i].option[m].item == score[lens-1]){
                                    questions[nextList].list[i].option[m].flag = 1;
                                }else{
                                    questions[nextList].list[i].option[m].flag = 2;
                                }
                            }
                            questions[nextList].list[i].values = scoreArr;
                        }
                        questions[nextList].list[i].value = score[0];
                    }
                }
            }
        }
    }
    /*
    * 遍历选项option，如果选中，flag = 1
     */
    var optionsStatus = function(question,option,value,type){
        for(var i = 0;i<option.length;i++){
            var val = option[i].item;
            if(type =="single"){
                if(val == value[0]){
                    option[i].flag = 1;
                }else{
                    option[i].flag = 2;
                }
                question.extralSingle = value[1];
                question.value = value[0];
            }else if(type == "checkbox"){
                if($.inArray(val,value) >= 0){
                    option[i].flag = 1;
                    question.value = val;
                }else{
                    for(var j = 0;j<value.length;j++){
                        if(value[j].indexOf("--") > 0){
                            var name = value[j].substring(0,value[j].indexOf("--"));
                            if(name == val){
                                option[i].flag = 1;
                                question.extralSingle = value[j].substring(value[j].indexOf("--")+2)
                                question.extralName = name;
                            }
                        }else{
                            option[i].flag = 2;
                        }
                    }
                    
                }
            }
        }
    }
    /*
    *多选 + 输入框的保存：
     */
    var quesCheckboxSave_osi = function(scoreObj,dom){
        var questionsnaire = $(dom).parents('.questionnaire_operate').siblings(".questionnaire");
        var nowId = questionsnaire.find('div[quesType="osi"]').attr("id");
        var flag = true;
        if(questionsnaire.find('div.link_checked').length == 0){
            flag = false;
            return;
        }
        if($("input").length > 0){
            if(!$.trim($("input").val())){
                flag = false;
                return;
            }
        }
        scoreObj["ques"][nowId] = [];
        if(questionsnaire.find('div.link_checked').length > 0 ){
             questionsnaire.find('div.link_checked').each(function(){
                var name = $(this).attr("name");
                if(name.indexOf("其他") == -1){
                    scoreObj["ques"][nowId].push(name);
                }else{
                    if($("input").length > 0){
                        scoreObj["ques"][nowId].push(name+"--"+$.trim($("input").val()));
                    }
                }
            });
        }
        return flag;
    }
    /*
    *  单选题：
     */
    var dealCss = function(link,isShow){
        for(var i = 0;i<link.length;i++){
            if(link[i].indexOf(".")>= 0){
                var splitId = link[i].split(".");
                link[i] = splitId.join("-");
            }
            if(isShow == 1){
                $("#"+ link[i]).css("display","block");
            }else{
                $("#"+ link[i]).css("display","none");
            }
        }
    }
    var quesSingleSave_osi = function(scoreObj,dom){
        var questionsnaire = $(dom).parents('.questionnaire_operate').siblings(".questionnaire");
        var nowId = questionsnaire.find('div[quesType="osi"]').attr("id");
        var flag = false;
        if(questionsnaire.find('div.link_checked').length == 0){
            flag = false;
            return;
        }
        var name = questionsnaire.find('div.link_checked').attr("name");
        if($("input[name='"+name+"']").length > 0){
            if( !$.trim($("input[name='"+name+"']").val())){
                flag = false;
                return;
            }
            scoreObj["ques"][nowId] = [name,$.trim($("input[name='"+name+"']").val())];
            flag = true;
        }else{
            scoreObj["ques"][nowId] = [name];
            flag = true;
        }
        return flag;
    }
    var quesSingleTabFn_osi = function(scoreObj,dom){
        $(dom).addClass("link_checked").siblings().removeClass("link_checked");
        var nowId = $(dom).parents('div[type="single"]').attr("id");
        var html = $(dom).html(),name = $(dom).attr("name");
        var choose=$(dom).parent().attr("choose");
        if(!choose){
            if($(dom).parents('div.panel').attr("type") == "single"){
                setTimeout(function(){
                    $("#box").find(".ques-click-group-osi button[group='next']").click();
                },100);
            }
        }
        
    }
    var quesCheckboxTabFn_osi = function(scoreObj,dom){
        var html = $(dom).html(),name = $(dom).attr("name");
        var choose=$(dom).parent().attr("choose");
        if(choose){var link=JSON.parse($(dom).parent().attr("link")); }
        if($(dom).hasClass("link_checked")){
            $(dom).removeClass("link_checked");
            if(choose){
                if(choose.indexOf(name) != -1){
                    if(choose.indexOf(';') > 0 && choose.indexOf(name+";") != -1){
                        dealCss(link);
                    }else if(choose == name){
                        dealCss(link);
                    }
                }
            }/*else{
                if(html.indexOf("其他") >= -1 ){
                    $(dom).parent().siblings(".extralSingle").html("");
                }
            }*/
        }else{
            $(dom).addClass("link_checked");
            if(choose){
                if(choose.indexOf(name) != -1){
                    if(choose.indexOf(';') > 0 ){
                        dealCss(link,1);
                    }else if(choose == name){
                        dealCss(link,1);
                    }
                }
            }/*else{
                if(html.indexOf("其他") >= 0 ){
                    $(dom).parent().siblings(".extralSingle").html('请填写：<input type="text" class="form-control w-150" name="'+name+'">');
                    $("input[name='"+name+"']").focus();
                }
            }*/
            
        }
    }
    /*
    * osi填空题：
     */
    var quesBlankFn_osi = function(scoreObj,dom){
        var questionsnaire = $(dom).parents('.questionnaire_operate').siblings(".questionnaire");
        var type = questionsnaire.find('div[quesType="osi"]').attr("type");
        var nowId = questionsnaire.find('div[quesType="osi"]').attr("id");
        if(type == "blank"){
            var flag = true,isEmoj = false;//判断是否填完：
            scoreObj["ques"][nowId] = [];
            questionsnaire.find('div[quesType="osi"]').find('.panel-body input').each(function(){
                if(!$(this).val()){//ios非数字时，获取为空，
                    if($(this).attr("type") == "number"){
                        isEmoj = "num";
                    }else{
                        flag = false;
                    }
                    return;
                }else{
                    isEmoj = isEmojiCharacter($(this).val());
                    if(isEmoj == "emo") return;
                }
            });
            questionsnaire.find('div[quesType="osi"]').find('.panel-body input').each(function(){
                scoreObj["ques"][nowId].push($(this).val());
            });
        }else if(type=="blankList"){
            var flag = false;//判断是否填完：
            scoreObj["ques"][nowId] = [];
            questionsnaire.find('div[quesType="osi"]').find('.panel-body textarea').each(function(){
                if($(this).val()){
                    isEmoj = isEmojiCharacter($(this).val());
                    if(isEmoj == "emo") return;
                    if(!isEmoj){ flag = true; return;}
                }
            });
            questionsnaire.find('div[quesType="osi"]').find('.panel-body textarea').each(function(){
                if($(this).val()){
                    scoreObj["ques"][nowId].push($(this).val());
                }
            });
            if(nowId == "I3" && scoreObj["ques"]["I2"]){//如果I2选择d/e;I3必填：
                if(scoreObj["ques"]["I2"][0] != "d" && scoreObj["ques"]["I2"][0] != "e"){
                    flag = true;
                }
            }
        }
        if(isEmoj == "emo" || isEmoj == "num"){
            flag = isEmoj;
        }
        return flag;
    }
    //osi_blankList:
    var addBlankFn = function(scoreObj,dom){
        if(!$(dom).prev('textarea').val()){
            $common.toastShow("当前输入框还未填写",2000);
            return;
        }else{
            var isEmoj = isEmojiCharacter($(dom).prev('textarea').val());
            if(isEmoj == "emo"){
                $common.toastShow("不可以输入表情符号",2000);
                return;
            }
        }
        var h = '<div class="clearfix"><textarea class="pull-left form-control blank_text"></textarea><button class="pull-left btn btn-pri" id="addBlank">添加</button></div>';
        $(dom).parents("div.blankList").append(h);
        $(dom).remove();
    }
    /*
    * 联动 + 单选+填空+多选：
     */
    var quesLinkageSaveFn_osi = function(scoreObj,dom){
        var questionsnaire = $(dom).parents('.questionnaire_operate').siblings(".questionnaire");
        questionsnaire.find('.panel-body>div[type]').each(function(){
            var nowId = $(this).attr("id");
            var type = $(this).attr("type");
            //存储：
            if(type == "single"){
                if($(this).find('div.link_checked').attr("name")){
                    scoreObj["ques"][nowId] = [$(this).find('div.link_checked').attr("name")]
                }
            }else if(type == "checkbox"){
                if($(this).find('div.link_checked').length > 0 ){
                    scoreObj["ques"][nowId] = [];
                     $(this).find('div.link_checked').each(function(){
                        scoreObj["ques"][nowId].push($(this).attr("name"));
                    });
                }
            }else if(type == "blankList"){
                var isFlag = false;
                scoreObj["ques"][nowId] = [];
                $(this).find('textarea').each(function(){
                    if(!isFlag){
                        if($(this).val()){isFlag = true;}
                    }
                    scoreObj["ques"][nowId].push($(this).val());
                    
                });
                if(!isFlag){
                    delete scoreObj["ques"][nowId];
                }
            }else if(type == "blank"){
                scoreObj["ques"][nowId] = [];
                var isFlag = true;
                $(this).find('input').each(function(){
                    if(isFlag){
                        if(!$(this).val() && $(this).val().length == 0){isFlag = false;}
                    }
                    scoreObj["ques"][nowId].push($(this).val());
                });
                if(!isFlag){
                    delete scoreObj["ques"][nowId];
                }
            }else if(type=="blankSingle"){
                scoreObj["ques"][nowId] = [];
                var isFlag = true,isEnding = true;
                $(this).find('input').each(function(){
                    if(isFlag){
                        if(!$(this).val() && $(this).val().length == 0){isFlag = false;}
                    }
                    scoreObj["ques"][nowId].push($(this).val());
                });
                if(!isFlag){
                    delete scoreObj["ques"][nowId];
                }else{
                    if($(this).find('div.link_checked').attr("name")){
                        scoreObj["ques"][nowId].push($(this).find('div.link_checked').attr("name"));
                    }
                }
            }
        });
        //判断是否做完：
        var flag = true,isEmoj = false;
        questionsnaire.find('.panel-body>div[type]').each(function(){
            var nowId = $(this).attr("id");
            var type = $(this).attr("type");
            if(type != "blankSingle"){
                var hasStyle = $(this).attr("style");
                if(!hasStyle){//没有style属性：必填项：
                    if(type == "blank"){
                        $(this).find("input").each(function(){
                            if(!$(this).val()){//ios非数字时，获取为空，
                                if($(this).attr("type") == "number"){
                                    isEmoj = "num";
                                }else{
                                    flag = false;
                                }
                                return;
                            }else{
                                isEmoj = isEmojiCharacter($(this).val());
                                if(isEmoj == "emo") {flag = isEmoj ; return};
                            }
                        });
                    }else{
                        if(!scoreObj["ques"][nowId]){
                            flag = false;
                            return;
                        }
                    }
                }else{ //具有style属性
                    var css = $(this).css("display");
                    if(css == "block"){
                        /**/
                        if(type == 'blank'){
                            $(this).find("input").each(function(){
                                if(!$(this).val()){//ios非数字时，获取为空，
                                    if($(this).attr("type") == "number"){
                                        flag = "num";
                                    }else{
                                        flag = false;
                                    }
                                    return;
                                }else{
                                    isEmoj = isEmojiCharacter($(this).val());
                                    if(isEmoj == "emo") {flag = isEmoj ; return};
                                }
                            });
                        }else{
                            if(!scoreObj["ques"][nowId]){
                                flag = false;
                                return 
                            }
                        }
                    }else if(css == "none"){
                        delete scoreObj["ques"][nowId];
                    }
                }
            }else{
                var inputVal = $(this).find(".ques").find("input[type='number']").val();
                if(inputVal == '0'){
                    flag = true;
                }else{
                    $(this).find('.inputNo').find("input").each(function(){
                        if(!$(this).val() && $(this).val().length == 0){
                            flag = false;
                            return;
                        }else{
                            isEmoj = isEmojiCharacter($(this).val());
                            if(isEmoj == "emo") return;
                        }
                    });
                    if($(this).find('div.link_checked').length == 0){
                        flag = false;
                        return;
                    }
                }
            }
            
        });
        if(isEmoj == "emo" || isEmoj == "num"){
            flag = isEmoj;
        }
        return flag;
    }
    var quesLinkageTabFn_osi = function(scoreObj,dom){
        var choose=$(dom).parent().attr("choose");
        if(choose){
            var name = $(dom).attr("name");
            //不同选项做不同的题目：
            if(choose.indexOf("[") >= 0 && choose.indexOf("]") >= 0){
                var chooseArr = JSON.parse(choose);
                var index = $.inArray(name,chooseArr);
                var link0=JSON.parse($(dom).parent().attr("link0"));
                var link1=JSON.parse($(dom).parent().attr("link1"));
                if(choose.indexOf(name) != -1){
                    if(index == 0){
                        dealCss(link1);
                        dealCss(link0,1);
                    }else if(index == 1){
                        dealCss(link0);
                        dealCss(link1,1);
                    }
                }else{
                    dealCss(link1);
                    dealCss(link0);
                }
            }else{
                //某些选项需要做题：
                var link=JSON.parse($(dom).parent().attr("link"));
                if(choose.indexOf(name) != -1){
                    if(choose.indexOf(';') > 0){
                        dealCss(link,1);
                    }else if(choose == name){
                        dealCss(link,1);
                    }else{
                        dealCss(link);
                    }
                }else{
                    dealCss(link);
                }
            }
        }
    }
    /*
    * 联动：
     */
    /*
    * 按钮组的隐藏显示：
     */
    event.btnGroupCss = function(showListNo,length){
        var arr = [];
        if(showListNo  == 1){//第一个展示1,2,3；
            arr = [1,2,3];
        }else if(length - showListNo == 0){//最后一个：展示length,length-1,length-2;
            arr = [length-2,length-1,length];
        }else{//其余情况展示：showListNo-1，lshowListNo，showListNo+1
            arr = [showListNo-1,showListNo,showListNo*1+1]
        }
        $("#ques-click-group-osi").find("button[type]").each(function(){
            var item = $(this).attr("item");
            if($.inArray(item*1 , arr) >= 0){
                $(this).css("display","block");
            }else{
                $(this).css("display","none");
            }
        });
    }
    /*
    * singleBlank：
     */
    var singleBlankClick_osi = function(scoreObj,dom){
        $(dom).addClass("link_checked").siblings().removeClass("link_checked");
    };
    var singleBlankInput_osi = function(scoreObj,dom){
        var max = $common.getNowFormatDate();
        if($(dom).val() && $(dom).val()!= "0"){
            var h= '';
            for(var i = 0 ; i<$(dom).val();i++){
                h +='<input class="form-control" type="date" name="singleNo" max = "'+max+'">';
            }
            $(dom).parent().siblings(".inputNo").html(h).css("display","block");
            $(dom).parent().siblings(".ques_single_tab").css("display","block");
        }else{
            $(dom).parent().siblings(".inputNo").html('').css("display","none");
            $(dom).parent().siblings(".ques_single_tab").css("display","none");
        }
    };
    //妇女健康调查问卷：
    event.init2 = function(questions,scoreObj,infoParams,length){
        //题目切换：
        $("#box").on("click",".ques-click-group-osi button",function(){
            var _this = this;
            topicSwitchingOSI(questions,scoreObj,_this,infoParams,length);
        });

        /*
        * OSI单选：single
        * */
        $("#box").on("click","div[type='single'] .linkage_tab",function(){
            var _this = this;
            quesSingleTabFn_osi(scoreObj,_this);
        });
        /*
        * OSI多选：checkbox
        * */
        $("#box").on("click","div[type='checkbox'] .linkage_tab",function(){
            var _this = this;
            quesCheckboxTabFn_osi(scoreObj,_this);
        });
        /*
        * OSI填空：blankList //上翻时遍历保存；
        * */
        $("#box").on("click","div[type='blankList'] #addBlank",function(){
            var _this = this;
            addBlankFn(scoreObj,_this);
        });
        $("#box").on("blur","div[type='blank'][quesType='osi'] input[type='number']",function(){
            if($(this).val() < 0){
                $common.toastShow("不可以输入小于0的值");
                $(this).val('').focus();
            }
        });

        /*
        * 联动题型：单选点击事件：
         */
        $("#box").on("click","div[type='linkage'] div[type='single'] .linkage_tab",function(){
            var _this = this;
            quesLinkageTabFn_osi(scoreObj,_this);
        });
        /*
        * singleBlank:试管婴儿技术：
        * */
        $("#box").on("blur","div[type='linkage'] div[type='blankSingle'] input[type='number']",function(){
            var _this = this;
            singleBlankInput_osi(scoreObj,_this);
        });
        $("#box").on("click","div[type='linkage'] div[type='blankSingle'] .linkage_tab",function(){
            var _this = this;
            singleBlankClick_osi(scoreObj,_this);
        });

        /*
        *  确认----跳转：#toSureNext
         */
        $("#box").off("click","#toSureNext");
        $("#box").on("click","#toSureNext",function(){
            $("#box").find(".ques-click-group-osi button[group='next']").click();
        });

        /*
        * number类型提示输入数字。text类型不能输入表情符号
         */
        $("#box").on("input propertychange","input",function(){
            if($(this).attr("type") == "number"){
                if(!$(this).val()){
                    $bb.toastShow("请输入数值",2000);
                    $(this).val("").focus();
                }
            }else if($(this).attr("type") == "text"){
                if($(this).val()){
                    if(isEmojiCharacter($(this).val())){
                        $bb.toastShow("不能输入表情",2000);
                        $(this).focus();
                    }
                }
            }else if($(this).attr("type") == "date"){
                //月经控制：
                var id = $(this).parents("div[type='blank']").attr("id");
                if(id == "2-3-1" || id == "2-3-2"){
                    if(id == "2-3-2"){
                        var val = $("#2-3-1").find("input[type='date']").val();
                    }else{
                        $("#2-3-2").find("input[type='date']").attr("max",$(this).val());
                        var val = $("#2-3-2").find("input[type='date']").val();
                    }
                    if(val && val == $(this).val()){
                        $(this).val("");
                        $common.toastShow("前后日期应该不同",2000);
                    }
                }
            }
        });
        $("#box").on("input propertychange","textarea",function(){
            if($(this).val()){
                if(isEmojiCharacter($(this).val())){
                    $bb.toastShow("不能输入表情",2000);
                    $(this).focus();
                }
            }
        });

    };
    /*
    * 判断是否输入表情符号：
     */
    var isEmojiCharacter = function(substring) {  
        var flag = false;
        for ( var i = 0; i < substring.length; i++) {  
            var hs = substring.charCodeAt(i);  
            if (0xd800 <= hs && hs <= 0xdbff) {  
                if (substring.length > 1) {  
                    var ls = substring.charCodeAt(i + 1);  
                    var uc = ((hs - 0xd800) * 0x400) + (ls - 0xdc00) + 0x10000;  
                    if (0x1d000 <= uc && uc <= 0x1f77f) {  
                        flag = "emo";   
                    }  
                }  
            } else if (substring.length > 1) {  
                var ls = substring.charCodeAt(i + 1);  
                if (ls == 0x20e3) {  
                    flag = "emo";   
                }  
            } else {  
                if (0x2100 <= hs && hs <= 0x27ff) {  
                    flag = "emo";  
                } else if (0x2B05 <= hs && hs <= 0x2b07) {  
                    flag = "emo";   
                } else if (0x2934 <= hs && hs <= 0x2935) {  
                    flag = "emo"; 
                } else if (0x3297 <= hs && hs <= 0x3299) {  
                    flag = "emo";  
                } else if (hs == 0xa9 || hs == 0xae || hs == 0x303d || hs == 0x3030  
                        || hs == 0x2b55 || hs == 0x2b1c || hs == 0x2b1b  
                        || hs == 0x2b50) {  
                    flag = "emo";  
                }  
            }  
        }  
        return flag;
    }  

    return event;
});